//
//  MoreServiceViewController.m
//  Housekeeping
//
//  Created by 辰领科技 on 16/5/27.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "MoreServiceViewController.h"
#import "ListTableViewCell.h"
#import "DetailedTableViewCell.h"
#import "HouseCleanViewController.h"
#import "PriceDifferenceViewController.h"
#import "MouthSerciveViewController.h"

static NSString *listCellIdentifier = @"ListTableViewCell";
static NSString *detailedCellIdentifier = @"DetailedTableViewCell";

@interface MoreServiceViewController ()
<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *listTableView;
@property (strong, nonatomic) IBOutlet UITableView *detailedTableView;

@property (nonatomic,assign)  int count;

@property (strong, nonatomic) UILabel *headerLabel;

@property (strong, nonatomic) NSArray *listArray;
@property (strong, nonatomic) NSMutableArray * rightArray;

@end

@implementation MoreServiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO =  1;
    _count = 0;
    _rightArray = [NSMutableArray array];
    [self initViewLayout];
    [self NetworkRequestlist];
    
}

- (void)initViewLayout {
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    
    [self.listTableView registerNib:[UINib nibWithNibName:listCellIdentifier bundle:nil] forCellReuseIdentifier:listCellIdentifier];
    [self.detailedTableView registerNib:[UINib nibWithNibName:detailedCellIdentifier bundle:nil] forCellReuseIdentifier:detailedCellIdentifier];
    
//头视图模块
    UIView *headerView = [[UIView alloc] initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 28), NO)];
    headerView.backgroundColor = [UIColor clearColor];
    self.detailedTableView.tableHeaderView = headerView;
    [headerView addSubview:self.headerLabel];
}




#pragma mark - <UITableViewDelegate && UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == self.listTableView) {
        return self.listArray.count;
    } else {
        return _rightArray.count;
    }
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.listTableView) {
        return 40*VerticalRatio();
    } else {
        return 65*VerticalRatio();
    }
    
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.listTableView) {
        ListTableViewCell *listCell = [self.listTableView dequeueReusableCellWithIdentifier:listCellIdentifier];
        if (!listCell) {
            listCell = [[ListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:listCellIdentifier];
        }
        
        listCell.listLabel.textColor = [UIColor colorWithWhite:0.306 alpha:1.000];
        
        if (indexPath.row == _count) {
            listCell.listLabel.textColor = [UIColor colorWithRed:254/255.0 green:150/255.0 blue:1/255.0 alpha:1];
        }
        
        
        listCell.listLabel.text = self.listArray[indexPath.row][@"mgtyName"];
        
        
        return listCell;
    } else {
        DetailedTableViewCell *detailedCell = [self.detailedTableView dequeueReusableCellWithIdentifier:detailedCellIdentifier];
        if (!detailedCell) {
            detailedCell = [[DetailedTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:detailedCellIdentifier];
        }
        
        self.headerLabel.text = self.listArray[_count][@"mgtyName"];
        
        if (indexPath.row == 0) {
            detailedCell.imageLabel.hidden = NO;
        } else {
            detailedCell.imageLabel.hidden = YES;
        }
        
        detailedCell.detailedLabel.text = self.rightArray[indexPath.row][@"goodsName"];
        detailedCell.viceDetailedLabel.text = self.rightArray[indexPath.row][@"mgooSubTitle"];
        

        return detailedCell;
    }

}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  
    if (tableView == self.listTableView) {
        
        _count = indexPath.row;
        [self.listTableView reloadData];
        [self.detailedTableView.header beginRefreshing];
    }else{
       
        NSString * serviceName = _rightArray[indexPath.row][@"goodsName"];
        if ([serviceName isEqualToString:@"补差价"]) {
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            PriceDifferenceViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"PriceDifference"];
            page.goodsId = [NSString stringWithFormat:@"%@",_rightArray[indexPath.row][@"goodsId"]];
            page.goodsName = [NSString stringWithFormat:@"%@",_rightArray[indexPath.row][@"goodsName"]];
            [[Common getNavigation]pushViewController:page];
        }else if ([serviceName isEqualToString:@"包月服务"]) {
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            MouthSerciveViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"MouthSercive"];
            page.goodsId = [NSString stringWithFormat:@"%@",_rightArray[indexPath.row][@"goodsId"]];
            page.goodsName = [NSString stringWithFormat:@"%@",_rightArray[indexPath.row][@"goodsName"]];
            [[Common getNavigation]pushViewController:page];
        }else{
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            HouseCleanViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"HouseClean"];
            page.goodsId = [NSString stringWithFormat:@"%@",_rightArray[indexPath.row][@"goodsId"]];
            [[Common getNavigation]pushViewController:page];
        }
    
    }
}

#pragma mark - 返回
- (IBAction)back:(id)sender {
    [self backBtn];
}


#pragma mark - Custom Accessor

- (UILabel *)headerLabel {
    if (!_headerLabel) {
        _headerLabel = [[UILabel alloc] init];
        _headerLabel.textColor = [UIColor colorWithRed:150/255.0 green:150/255.0 blue:150/255.0 alpha:1];
        _headerLabel.font = [UIFont systemFontOfSize:10];
        _headerLabel.frame = flexibleFrame(CGRectMake(8, 10, 50, 20), NO);
    }
    return _headerLabel;
}

#pragma mark - 网络请求
- (void)NetworkRequestlist {
    NSMutableDictionary * listDic = [NSMutableDictionary dictionary];
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:listDic withPath:HK_queryMallGoodsType withHttpType:@"POST" withTag:HK_HK_queryMallGoodsType];
    
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.detailedTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.detailedTableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self NetworkRequestRight];
        });
    }];
    // 马上进入刷新状态
    [self.detailedTableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.rightArray.count == _totle) {
        [self.detailedTableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self NetworkRequestRight];
        });
    }
    
}

#pragma mark   === 右侧数据
- (void)NetworkRequestRight {
    
    NSMutableDictionary * rightDic = [NSMutableDictionary dictionary];
    [rightDic setObject:self.listArray[_count][@"mgtyId"] forKey:@"mgtyId"];
    [rightDic setObject:[NSNumber numberWithInt:_pageNO] forKey:@"page"];
    [rightDic setObject:[NSNumber numberWithInt:PageSize] forKey:@"pageSize"];
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:rightDic withPath:HK_queryAppMallGoodsInfo withHttpType:@"POST" withTag:HK_HK_queryAppMallGoodsInfo];
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_detailedTableView.header endRefreshing];
    [_detailedTableView.footer endRefreshing];
    if (tag == HK_HK_queryMallGoodsType){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        }else  {
            self.listArray = database[@"result"];

            self.listTableView.delegate = self;
            self.listTableView.dataSource = self;
            [self.listTableView reloadData];
            if (_typeStr) {
                for (int i = 0; i<_listArray.count; i++) {
                    NSDictionary * dic = _listArray[i];
                    if ([dic[@"mgtyId"]isEqualToString:_typeStr]) {
                        _count = i;
                    }
                }
            }
            [self addRefreshing];
        }
    }else if (tag == HK_HK_queryAppMallGoodsInfo){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                                _totle = [database[@"result"][@"total"] integerValue];
                                if (_totle > PageSize) {
                                    __weak __typeof(self) weakSelf = self;
                                    if (!self.detailedTableView.footer) {
                                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                                        self.detailedTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                                            [weakSelf loadMoreData];
                                        }];
                                    }
                                }
                                if (self.pageNO == 1) {
                                    [self.rightArray removeAllObjects];
                                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.rightArray addObject:entity];
                }
                _detailedTableView.dataSource = self;
                _detailedTableView.delegate = self;
                [_detailedTableView reloadData];
                
                });
            
            }
                           
        }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [self dismissWaitDialog];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
